package cn.itlaobing.web.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBhelper {
	private Connection conn;
	private PreparedStatement ps;
	private ResultSet rs;
	private static String DRIVER="com.mysql.jdbc.Driver";
	private static String URL="jdbc:mysql://localhost:3306/listdb";
	private static String USER="root";
	private static String PWD="root";
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	private void openConnection() throws SQLException{
		if(conn==null||conn.isClosed()) {
			conn=DriverManager.getConnection(URL, USER, PWD);
		}
	}
	public void close() throws SQLException{
		if(!conn.isClosed()||conn!=null) {
			conn.close();
		}
		if(ps!=null) {
			ps.close();
		}
		if(rs!=null) {
			rs.close();
		}
	}
	private void SetPramater(Object...objs) throws SQLException{
		if(objs!=null||objs.length>0) {
			for(int i=0;i<objs.length;i++) {
				ps.setObject(i+1,objs[i]);
			}
		}
	}

	/**
	 * 增删改的辅助方法
	 * @param sql
	 * @param objs
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public int executeUpdate(String sql,Object...objs) throws SQLException,IOException{
		openConnection();
		ps=conn.prepareStatement(sql);
		SetPramater(objs);
		return ps.executeUpdate();
	}

	/**
	 * 查询的辅助方法
	 * @param sql
	 * @param objs
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public ResultSet executeQuery(String sql,Object...objs) throws SQLException,IOException{
		openConnection();
		ps=conn.prepareStatement(sql);
		SetPramater(objs);
		return ps.executeQuery();
	}
	
}
